package com.ruoyi.carton.service;


import com.ruoyi.carton.domain.Box;
import com.ruoyi.carton.domain.OrderStatus;
import com.ruoyi.carton.domain.Orders;
import com.ruoyi.carton.domain.vo.ExcelVO;
import com.ruoyi.carton.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class ExcelImportService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private BoxService boxService;

    @Autowired
    private OrderRequestService orderRequestService;

    @Transactional
    public void saveExcelData(List<ExcelVO> list) {
        for (ExcelVO vo : list) {

            // Step 1: 检查并写入 box 表
            String boxId = vo.getProductId();
            if (!boxService.lambdaQuery().eq(Box::getId, boxId).exists()) {
                Box box = new Box();
                box.setId(boxId);
                box.setProductName(vo.getProductName());
                box.setLength(vo.getLength());
                box.setWidth(vo.getWidth());
                box.setHeight(vo.getHeight());
                box.setOrderQuantity(vo.getOrderQuantity());
                box.setFluteType(vo.getFluteType());
                box.setArea(vo.getArea());
                box.setSalePrice(vo.getSalePrice());
                box.setRebate(BigDecimal.ZERO);
                box.setProfit(box.getSalePrice());
                boxService.save(box);
            }

            // Step 2: 检查并写入 orders 表
            String orderId = vo.getId();
            if (!ordersService.lambdaQuery().eq(Orders::getId, orderId).exists()) {
                Orders order = new Orders();
                order.setId(orderId);
                order.setCustomerName(vo.getCustomerName());
                order.setProductId(boxId); // 外键依赖 box.id
                // 字符串转Date
                Date entryDate = null;
                try {
                    entryDate = DateUtils.parseDate(vo.getEntryDate());
                } catch (RuntimeException e) {
                    throw new RuntimeException("订单ID " + orderId + " 日期格式错误: " + vo.getEntryDate());
                }
                order.setEntryDate(entryDate);
                // 可以初始化订单状态为草稿
                order.setStatus(OrderStatus.DRAFT);

                ordersService.save(order);
            }
            // Step 3: 检查并写入 order_request 表
//            if (!orderRequestService.lambdaQuery().eq(OrderRequest::getOrderId, orderId).exists()) {
//                OrderRequest orderRequest = new OrderRequest();
//                orderRequest.setOrderId(orderId);
//                orderRequest.setBoxProductId(boxId);// 外键依赖 box.id
//                orderRequestService.save(orderRequest);
//            }

        }
    }
}
